<script setup name="addModel">
import { useRouter } from 'vue-router'
import stepsList from './config/steps'
import { findNodeFlexible } from '@/utils/common'
import { ArrowRightBold } from '@element-plus/icons-vue'
import {
	DataSource,
	NotFound,
	TargetFeatureColumn,
	ModelSaveAndApplication,
	ModelingSubject, // 合并建模和评估功能
} from './components'

import { ElMessage } from 'element-plus'

// 步骤索引常量
const STEP_INDEX = {
	DATA_SOURCE: 0,
	TARGET_FEATURE: 1,
	MODELING: 2,
	SAVE_APPLY: 3,
}

const router = useRouter()
const steps = ref([
	{
		states: ['数据源'],
		component: 'DataSource',
		options: stepsList,
	},
])

const isIndex = ref(0)
const componentRef = ref(null)
const componentKey = ref(0)

// 简化formData结构
const formData = ref({
	// 数据源
	uploadedFile: null,
	fileData: '',
	fileName: '',
	originalName: '',
	tableData: [],
	tableColumns: [],

	// 目标特征列
	targetFeatureTable: [],
	imageData: '',

	// 主体模型（合并建模+评估）
	dropdownRefs: {}, // 下拉框ref数组，用于获取下拉框的值
	formRefs: {}, // 表单ref对象，用于获取表单的值
	modelEvaluationRefs: {},
	state: {
		modelTabs: [], // 标签页
		modelList: [], // 模型列表
		activeTabIndex: -1, // 当前激活的标签页索引
		activeNames: ['分类', '回归'], // 折叠面板激活状态
	}, // 状态对象，用于存储当前步骤的状态信息
})

// 组件映射
const componentMap = {
	DataSource,
	TargetFeatureColumn,
	ModelSaveAndApplication,
	ModelingSubject, // 合并组件
	NotFound,
}

// 当前组件
const isComponent = computed(() => {
	return steps.value[isIndex.value]?.component || 'NotFound'
})

// 文件名变化监听
watch(
	() => formData.value.fileName,
	(val) => {
		if (steps.value.length > 2 && isIndex.value === STEP_INDEX.DATA_SOURCE) {
			handleStepsChange(['数据源'], STEP_INDEX.DATA_SOURCE)
			Object.assign(formData.value, {
				imageData: '',
				// 主体模型（合并建模+评估）
				dropdownRefs: [], // 下拉框ref数组，用于获取下拉框的值
				formRefs: {}, // 表单ref对象，用于获取表单的值
				state: {
					modelTabs: [], // 标签页
					modelList: [], // 模型列表
					activeTabIndex: -1, // 当前激活的标签页索引
					activeNames: ['分类', '回归'], // 折叠面板激活状态
				}, // 状态对象，用于存储当前步骤的状态信息
			})
		}
	},
	{ deep: true, immediate: true }
)

// 步骤切换逻辑
const handleStepsChange = async (value, index) => {
	if (!value) return

	// 步骤切换前校验（跳过第一步）
	if (index !== STEP_INDEX.DATA_SOURCE && componentRef.value?.verification) {
		try {
			const valid = await componentRef.value.verification()
			if (!valid) {
				steps.value[index].states = []
				return
			}
		} catch (error) {
			ElMessage.error('步骤验证失败')
			return
		}
	}

	if (!value?.length) {
		steps.value.splice(index + 1)
		return
	}

	const currentValue = value[value.length - 1]
	const { node } = findNodeFlexible(stepsList, 'value', currentValue)

	steps.value.splice(index + 1)

	if (node) {
		const prevComponent = steps.value[index].component
		steps.value[index].component = node.component

		if (node.steps?.length > 0) {
			steps.value.push({
				states: [],
				options: node.steps,
			})
		}

		if (prevComponent !== node.component) {
			componentKey.value++
		}
	}

	isIndex.value = index
}

const handleClear = (index) => {
	if (index !== steps.value.length - 1) {
		steps.value.splice(index + 1)
	}
	if (index === isIndex.value) {
		steps.value[index].states = []
		steps.value[index].component = ''
	}
	isIndex.value = index - 1 || 0
}

const handleStepClick = async (index) => {
	if (steps.value[index].states.length > 0) {
		if (
			steps.value[index].component !== steps.value[isIndex.value]?.component
		) {
			componentKey.value++
		}
		isIndex.value = index
	}
}

// 第三步提交（进入第四步）
const handleSubmit = async () => {
	try {
		if (componentRef.value?.verification) {
			const valid = await componentRef.value.verification()
			if (!valid) return
		}

		steps.value.splice(isIndex.value + 1)
		steps.value.push({
			states: ['模型保存与应用'],
			component: 'ModelSaveAndApplication',
			options: [{ label: '模型保存与应用', value: '模型保存与应用' }],
		})

		isIndex.value = steps.value.length - 1
		componentKey.value++
		ElMessage.success('进入模型应用阶段')
	} catch (error) {
		ElMessage.error('提交失败')
	}
}

// 按钮显示逻辑
const shouldShowSubmitButton = computed(() => {
	return isIndex.value === STEP_INDEX.MODELING
})

const shouldShowCompleteButton = computed(() => {
	return isIndex.value === STEP_INDEX.SAVE_APPLY
})

onMounted(() => {
	handleStepsChange(['数据源'], STEP_INDEX.DATA_SOURCE)
})
</script>

<template>
	<div class="addModel">
		<div class="addModel-header">
			<span style="display: flex; align-items: center">
				<span class="addModel-header-title"> 机器学习 </span>
			</span>

			<div class="header-actions">
				<!-- 第三步提交按钮 -->
				<el-button
					type="primary"
					@click="handleSubmit"
					v-if="shouldShowSubmitButton && false"
					:disabled="true"
				>
					提交
				</el-button>

				<!-- 第四步完成按钮 -->
				<el-button
					type="success"
					@click="router.back()"
					v-if="shouldShowCompleteButton"
				>
					完成
				</el-button>
			</div>
		</div>
		<div class="addModel-content">
			<div class="addModel-content-step">
				<div
					v-for="(item, index) in steps"
					:key="index"
					class="addModel-content-step-item"
					:class="{ active: isIndex === index }"
					@click.stop="handleStepClick(index)"
				>
					<el-cascader
						v-model="item.states"
						:options="item.options"
						:props="{
							value: 'value',
							label: 'label',
							children: 'children',
							expandTrigger: 'hover',
						}"
						:placeholder="`选择第${index + 1}步`"
						:show-all-levels="false"
						:clearable="index !== 0"
						@change="(value) => handleStepsChange(value, index)"
						@clear="handleClear(index)"
						:class="{ 'addModel-content-step-item-active': index === isIndex }"
					/>
					<el-icon
						v-if="index < steps.length - 1"
						class="addModel-content-step-item-icon"
						><ArrowRightBold
					/></el-icon>
				</div>
			</div>
			<div class="addModel-content-component">
				<component
					:is="componentMap[isComponent] ?? NotFound"
					v-model="formData"
					:node="steps[isIndex].states[steps[isIndex].states.length - 1]"
					ref="componentRef"
					:key="componentKey"
				/>
			</div>
		</div>
	</div>
</template>

<style scoped lang="scss">
.addModel {
	&-header {
		display: flex;
		align-items: center;
		height: 60px;
		border-bottom: 1px solid #e5e5e5;
		box-sizing: border-box;
		padding: 0 20px;
		background-color: #fff;
		justify-content: space-between;

		&-title {
			font-size: 16px !important;
			font-weight: bold;
			margin-left: 10px;
		}
	}
	&-content {
		background-color: #fff;
		min-height: calc(100vh - 170px);

		box-sizing: border-box;
		overflow-y: auto;
		border-radius: 10px;
		padding: 20px 20px 0 20px;

		&-step {
			display: flex;
			height: 60px;
			align-items: center;
			border-bottom: 1px solid #e5e5e5;
			padding-bottom: 10px;
			box-sizing: border-box;
			&-item {
				display: flex;
				align-items: center;
				:deep(.el-cascader) {
					width: 200px;
				}
				&-icon {
					width: 40px;
					color: #dcdfe6;
				}
				:deep(.addModel-content-step-item-active) {
					box-sizing: border-box;
					.el-input__wrapper {
						border: 1px solid var(--el-color-primary);
					}
				}
			}
		}
		&-component {
		}
	}
}

// 训练状态样式
.training-status {
	display: flex;
	align-items: center;
	margin-right: 16px;

	.training-text {
		font-size: 14px;
		color: #606266;
		white-space: nowrap;
	}
}
</style>
